package threads;

import android.content.Context;
import android.os.Environment;
import android.os.Message;
import android.util.Log;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

import constants.Constants;
import constants.HandlerConstant;
import customhandler.MyHandler;
import serialport.DealFingerprintSerialPortData;
import singleton.SingletonClass;
import utils.DigitalTrans;
import utils.TimeUtil;

/**
 * Created by admin on 2018/1/16.
 */
public class FingerprintSerialPortReadThread extends BaseThread {
    private InputStream mInputStream;
    private OutputStream mOutputStream;
    private Context mContext;
    private DealFingerprintSerialPortData dealData;
    private ByteArrayOutputStream baos;
    private MyHandler allHandler;
    private DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss");
    private int delayMillis = 1000;//dalayMillis后将isLengthEqualEight重置,防止丢包等情况发生时,isLengthEqualEight无法重置(注意:要保证delayMillis时间内数据要接收完成)
    //收到的字节长度的总数
    private int count;
    private boolean isLengthEqualEight = true;//判断字节数是否大于8,在31等数据包头部,接下来就是大于8个字节的数据,因此在收到31等头部之后,将isLengthEqualEight置为true
    private int dataLength;//大于8个字节时,包的头部(8个字节)与数据包的字节数的总和
    private int number;

    @Override
    public void run() {
        super.run();

        if (Constants.IS_OLD_ANDROID) {
            int size = 0;
            while (!isInterrupted()) try {
                byte[] buffer = new byte[1024];
                if (mInputStream == null) {
                    return;
                }
                size = mInputStream.read(buffer);
                if (size > 0) {
                    //模组返回的数据是8个字节
                    byte[] bs = new byte[size];
                    System.arraycopy(buffer, 0, bs, 0, size);
                    if (isLengthEqualEight) {
                        saveToFile(DigitalTrans.toHexString(bs));
                        if (bs.length > 1) {
                            int commandType = bs[1] & 0xFF;
                            if (commandType == 0x23 || commandType == 0x24 || commandType == 0x26 || commandType == 0x28 || commandType == 0x2B || commandType == 0x2D || commandType == 0x31) {
                                int result = bs[4] & 0xFF;
                                //命令执行成功
                                if (result == Constants.ACK_SUCCESS) {
                                    dataLength = Integer.parseInt(DigitalTrans.toHexStringByte(bs[2]) + DigitalTrans.toHexStringByte(bs[3]), 16);
                                    baos.reset();
                                    count = 0;
                                    isLengthEqualEight = false;
                                    count += bs.length;
                                    baos.write(bs, 0, bs.length);
                                    sendEmptyFrameMessageDelay(HandlerConstant.RESET, delayMillis);
                                } else {
                                    dealData.fingerprintResult(result);
                                    //命令执行失败
                                }
                            } else {
                                dealData.receiveData(bs);
                            }
                        }

                    } else {
                        //模组返回的数据大于8个字节
                        count += bs.length;
                        baos.write(bs, 0, bs.length);
                        //dataLength是真实的数据,加上头部包,8个字节,以及数据包的头尾和校验位3个字节
                        if (count == dataLength + 11) {
                            byte[] bytes = baos.toByteArray();
//                        String completeData = ;
                            dealData.receiveData(bytes);
//                        dealData.dealMoreThanEightData(completeData,bs[1] & 0xFF);
//                        Log.e("TAG", "run: " + DigitalTrans.toHexString(bytes).length());
//                        Log.e("TAG", "run: " + DigitalTrans.toHexString(bytes));
                            isLengthEqualEight = true;

                            String substring = DigitalTrans.toHexString(bytes);
                        }
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }else {
            runNewAndroid();
        }
    }

    public FingerprintSerialPortReadThread(InputStream mInputStream, OutputStream mOutputStream, Context mContext) {
        this.mInputStream = mInputStream;
        this.mOutputStream = mOutputStream;
        this.mContext = mContext;
        allHandler = SingletonClass.getSingleton(MyHandler.class);
        dealData = new DealFingerprintSerialPortData(mOutputStream, mContext);
        baos = new ByteArrayOutputStream();
    }

    @Override
    public void onHandleFrameMessage(Message msg) {
        switch (msg.what) {
            case HandlerConstant.RESET:
                isLengthEqualEight = true;
                break;
        }
    }

    public void saveToFile(String receiveData) {
        StringBuffer sb = new StringBuffer();
        try {
            if (Environment.getExternalStorageState().equals(
                    Environment.MEDIA_MOUNTED)) {

                String time = formatter.format(new Date());
                sb.append(time);
                sb.append("  --begin--:  ");
                sb.append(receiveData);
                sb.append("  --end--;  ");
                sb.append("\r\n");
                String fileName = TimeUtil.getYear() + "-" + (TimeUtil.getMonth() + 1) + "-" + TimeUtil.getDay() + ".log";
                String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/fingerprint/";
                File dir = new File(path);
                if (!dir.exists()) {
                    dir.mkdirs();
                }
                FileOutputStream fos = new FileOutputStream(path + fileName, true);
                fos.write(sb.toString().getBytes());
                fos.flush();
                fos.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void runNewAndroid() {
        int size = 0;
        while (!isInterrupted()) try {
            byte[] buffer = new byte[1024];
            if (mInputStream == null) {
                return;
            }
            Log.e("GGG", "receiveData: ");
            size = mInputStream.read(buffer);
            if (size > 0) {
                //模组返回的数据是8个字节
                byte[] bs = new byte[size];
                System.arraycopy(buffer, 0, bs, 0, size);
                Log.e("GGG", "runNewAndroid: " + DigitalTrans.toHexString(bs));
                int i = bs[0] & 0xFF;
                if (isLengthEqualEight) {
                    if (number == 0) {
                        if (i == 0xF5) {
                            Log.e("GGG", "bs[0] == 0xF5 ");
                            baos.reset();
                            baos.write(bs, 0, bs.length);
                        }
                    } else {
                        baos.write(bs, 0, bs.length);
                    }
                    number += bs.length;
                }else {
                    number = 8;
                }
//                Log.e("GGG", "number  :  dataLength    " + number + "  " + (dataLength+8) );
                if (number >= 8) {
//                    Log.e("GGG", " number = 0");
                    number = 0;
                    if (isLengthEqualEight) {
                        bs = baos.toByteArray();
                        Log.e("GGG", "number == 2 : " + DigitalTrans.toHexString(bs));
                        saveToFile(DigitalTrans.toHexString(bs));
                        if (bs.length > 1) {
                            int commandType = bs[1] & 0xFF;
//                            Log.e("GGG", "commandType: " +commandType  );
                            if (commandType == 0x23 || commandType == 0x24 || commandType == 0x26 || commandType == 0x28 || commandType == 0x2B || commandType == 0x2D || commandType == 0x31) {
                                int result = bs[4] & 0xFF;
//                                Log.e("GGG", "result: " + result);
                                //命令执行成功
                                if (result == Constants.ACK_SUCCESS) {
                                    dataLength = Integer.parseInt(DigitalTrans.toHexStringByte(bs[2]) + DigitalTrans.toHexStringByte(bs[3]), 16);
                                    Log.e("GGG", "dataLength: " + dataLength );
                                    count = 0;
                                    isLengthEqualEight = false;
                                    count += bs.length;
                                    Log.e("GGG", "dataLength: " + bs.length );
//                                    baos.write(bs, 0, bs.length);
                                    sendEmptyFrameMessageDelay(HandlerConstant.RESET, delayMillis);
                                    Log.e("GGG", "success: " + DigitalTrans.toHexString(bs));
                                    Log.e("GGG", "success: 成功");
                                } else {
                                    dealData.fingerprintResult(result);
                                    baos.reset();
                                    Log.e("GGG", "faild: " + result);
                                    Log.e("GGG", "faild: 失败");
                                    //命令执行失败
                                }
                            } else {
                                Log.e("GGG", "isLengthEqualEight: true   " + DigitalTrans.toHexString(bs));
                                dealData.receiveData(bs);
                                baos.reset();
                            }
                        }

                    } else {
                        //模组返回的数据大于8个字节
                        count += bs.length;
                        baos.write(bs, 0, bs.length);
                        Log.e("GGG", ">8: bs.length   " + bs.length);
                        Log.e("GGG", ">8: " + count + "  ::  " + dataLength);
                        //dataLength是真实的数据,加上头部包,8个字节,以及数据包的头尾和校验位3个字节
                        if (count == dataLength + 11) {
                            byte[] bytes = baos.toByteArray();
//                        String completeData = ;
                            String substring = DigitalTrans.toHexString(bytes);
                            Log.e("GGG", ">8: " + substring);
                            dealData.receiveData(bytes);
                            baos.reset();
//                        dealData.dealMoreThanEightData(completeData,bs[1] & 0xFF);
//                        Log.e("TAG", "run: " + DigitalTrans.toHexString(bytes).length());
//                        Log.e("TAG", "run: " + DigitalTrans.toHexString(bytes));
                            isLengthEqualEight = true;

                        }
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
